import instance from "../utils/request"
import Vue from "vue"
import router from "../router"
import { Notify } from 'vant';
import {base_url} from '../utils/baseURL'
Vue.use(Notify);
export default{
    namespaced:true,
    state(){
        return{
            pathFromSta:'/home',
            userinfo:null,
            cartGoods:null,
            fromDetail:0,
        }
    },
    getters:{
        allGoodsCount(state){
            return state.cartGoods ? state.cartGoods.reduce((pre,val)=>{
                return pre + val.num*1
            },0) : 0;
        },
        cartData(state){
            let isAllChecked = true;
            for(let i = 0; i < state.cartGoods.length; i++){
                if(!state.cartGoods[i].isChecked){
                    isAllChecked = false;
                    break
                }
            }
            return {isAllChecked} 
        },
        addressList(state){
            return state.addressInfos;
        },
        checkedGoods(state){
            let checkedArr = [],checkedId = [];
            state.cartGoods.forEach(item=>{
                if(item.isChecked){
                    checkedArr.push(item);
                    checkedId.push(item._id)
                }
            })
        }
    },
    mutations:{
        noneCheckedMut(state){
            if(state.cartGoods){
                for(var i = state.cartGoods.length - 1; i >= 0; i--){
                    let val = state.cartGoods[i];
                    val.isChecked = false;
                    state.cartGoods.splice(i,1,val)
                }
            }
        },
        editEndMut(state,oldgoods){
            if(state.cartGoods){
                for(var i = state.cartGoods.length - 1; i >= 0; i--){
                    oldgoods.forEach(item=>{
                        if(item._id == state.cartGoods[i]._id){
                            console.log(item._id)
                            state.cartGoods.splice(i,1,item);
                        }
                    })
                }
            }
        },
        addAddressMut(state,obj){
            state.addressInfos.splice(0,0,obj);
        },
        deleteGoodsMut(state,arr){
            for(var i = arr.length - 1; i >= 0; i--){
                state.cartGoods.forEach((item,index)=>{
                    if(item._id == arr[i]){
                        state.cartGoods.splice(index,1);
                    }
                })
            }
            state.cartGoods.length || (state.cartGoods = null);
        },
        cartCheckMut(state, idx) {//单选按钮
            state.cartGoods[idx].isChecked = !state.cartGoods[idx].isChecked;
        },
        cartAllCheckMut(state,bool){ 
            state.cartGoods.forEach(item=>{
                item.isChecked = !bool
            })
        },
        changeGoodNumMut(state,obj){
            obj.rst == "+" 
            ? state.cartGoods[obj.index].num++ 
            : state.cartGoods[obj.index].num--
        },
        pathFromMut(state,pname){//记录from路由,用于点击返回
            state.pathFromSta = pname;
        },
        userObjMut(state,obj){//保存用户的账号密码
            state.userinfo = obj;
        },
        cartGoodsMut(state,obj){ //保存请求到的用户商品信息
            state.cartGoods = obj;
        },
        changeFromMut(state,num){ //判断登录后是去详情页还是个人中心
            state.fromDetail = num ? num : 0;
        },
        cartChangeMut(state,obj){//更改用户商品或地址信息
            if(obj.Idx == 1 && state.cartGoods){
                for(var i = 0; i < state.cartGoods.length; i++){
                    if(state.cartGoods[i].id == obj.newgood.id &&
                        state.cartGoods[i].bgs.toString() == obj.newgood.bgs.toString()){
                            state.cartGoods[i].num += obj.newgood.num;
                            return;
                    }
                }
                state.cartGoods.push(obj.newgood);
            }else if(obj.Idx == 2){
                console.log(obj.changedata);
                let {num,bgs,index} = obj.changedata
                let changedGoods =  state.cartGoods[index];
                changedGoods.num = num;
                changedGoods.bgs = bgs;
                state.cartGoods.splice(index,1,changedGoods);
            }
        }
    },
    actions:{
        userLoginAct(context,values){
            instance.get( `${base_url}users`,{
                params:values
            }).then(res=>{
                console.log(res);
                if(res.data.code==1){
                    let {userinfo,token} = res.data.data
                    context.commit('userObjMut',userinfo);
                    sessionStorage.userinfo = JSON.stringify(userinfo);
                    sessionStorage.token = token;
                    Notify({ type: 'success', message: '登录成功！' });
                    instance.get( `${base_url}cartgoods`,{
                        params:{
                            userId:userinfo._id
                        }
                    }).then(res=>{
                        context.commit('cartGoodsMut',res.data.data);
                    })
                    if(!!context.state.fromDetail){
                        router.push('/detail/'+context.state.fromDetail)
                    }else{
                        context.commit('changeFromMut',0);
                        router.push('/')
                    }
                }else{
                    Notify({ type: 'danger', message: '登录失败，请确认用户名或密码正确!' });
                }
            })
        },
        cartChangeAct(context,obj){//obj中不传Idx表示直接请求，传了根据值做相应操作
            if(obj.Idx){
                context.commit('cartChangeMut',obj);
                let url = `${base_url}cartgoods`
                if(obj.Idx == 1){
                    instance.post(url,obj.newgood)
                }else if(obj.Idx == 2){
                    instance.put(url,obj.changedata)
                }
            }
        },
        changeCheckedAct(context,obj){
            let url = `${base_url}cartgoods`;
            let userId = JSON.parse(sessionStorage.userinfo)._id
            if(obj.type == "oneChange"){
                context.commit('cartCheckMut',obj.index)
                if(obj.isShow){return};
                instance.put(url,{_id:obj._id,isChecked:!obj.bool})
            }else if(obj.type == "allChange"){
                context.commit('cartAllCheckMut',obj.bool)
                if(obj.isShow){return};
                instance.put(url,{userId,isChecked:!obj.bool})
            }else if(obj.type == "changeNum"){
                context.commit('changeGoodNumMut',obj)
                instance.put(url,{_id:obj._id,num:obj.num}).then(res=>{
                    console.log(res);
                })
            }else if(obj.type == "delete"){
                context.commit('deleteGoodsMut',obj.where)
                console.log(obj.where);
                instance.delete(url,{
                    params:{
                        _ids:obj.where
                    }
                }).then(res=>{
                    console.log(res);
                })
            }else if(obj.type == "addAddress"){
                context.commit('addAddressMut',obj.newAddress)
            }
            // let id = JSON.parse(sessionStorage.userObj).id
            // // console.log(context.state.userData)
            // // console.log(obj.newAddress.isDefault)
            // // if(obj.newAddress.isDefault){
            // //     for(var i=0;i<=context.state.userData.addressInfos.length-1;i++){
            // //         context.state.userData.addressInfos[i].isDefault=false
            // //     }
            // // }
            // let url = 'http://localhost:3000/userdata/' + id;
            // instance.put(url,context.state.userData).then((res)=>{
            //     context.commit('userDataMut',res.data)
            // })
        },

       


    }
}